<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<style>
    td {
        word-break: keep-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

</style>
<link rel="stylesheet" href="${pageContext.request.contextPath}/res/jstree/themes/default/style.min.css" />

<script>
    //邮件项点击事件
    function readMail(s) {
        $("#sendButton").html("返回邮件列表");
        $("#variableContent").html("");
        var id = $(s).parent().parent().attr("id");
        var map = {'id': id};

        setRead([id], false);
        $.post('${pageContext.request.contextPath}/mail/read.shtml', map, function (data) {
            $("#variableContent").append(data);
        });
    }

    function setRead(ids, isread) {
        var map = {"ids": ids, "isread": isread};
        $.post('${pageContext.request.contextPath}/manager/setRead.shtml', map,function (){
            $('#listLabel').nextAll(".boxitem").remove();

            //显示邮箱列表
            function appendBoxList(){
                $.get('${pageContext.request.contextPath}/mail/boxList.shtml', function (data) {
                    $("#listLabel").after(data);
                });
            }

            appendBoxList();

            $('#inbox').children().remove();

            //获取未读邮件个数
            function showUnreadNumber(emailAccount){
                $.post('${pageContext.request.contextPath}/manager/showUnreadNumber.shtml',{"emailAccount":emailAccount}, function (data) {
//                alert(emailAccount);
                    if(data > 0){
                        $("#inbox").append("<span class='label label-primary pull-right'>"+data+"</span>");
                    }
                });
            }

            showUnreadNumber('${sessionScope.currentEmail.account}');
        });

    }

</script>


<!-- Horizontal Form -->
<div id="mailboxlist" style="display: block;">
    <div class="box-header with-border">
        <h3 class="box-title">收件箱</h3>

        <div class="box-tools pull-right">
            <div class="has-feedback">
                <input type="text" class="form-control input-sm"
                       placeholder="Search Mail" id="searchText"> <span
                    class="glyphicon glyphicon-search form-control-feedback" id="searchBtn"></span>
            </div>
        </div>
        <!-- /.box-tools -->
    </div>
    <!-- /.box-header -->
    <div class="box-body no-padding">
        <div class="mailbox-controls">
            <!-- Check all button -->
            <button type="button"
                    class="btn btn-default btn-sm checkbox-toggle " id="checkall">
                <i class="fa fa-square-o"></i>
                <%--<i class="fa fa-check-square-o"></i>--%>
            </button>
            <div class="btn-group">
                <button type="button" class="btn btn-default btn-sm" id="markIsRead">
                    <i class="fa fa-envelope-o"></i>
                </button>
                <button type="button" class="btn btn-default btn-sm">
                    <i class="fa fa-reply"></i>
                </button>
                <button type="button" class="btn btn-default btn-sm">
                    <i class="fa fa-share"></i>
                </button>
            </div>
            <!-- /.btn-group -->
            <button type="button" class="btn btn-default btn-sm" id="deleteMessage">

                    <i class="fa fa-trash-o"></i>

            </button>

            <!-- /.pull-right -->
        </div>

        <!-- table -->
        <div class="table-responsive mailbox-messages">
            <table class="table table-hover table-striped">
                <tbody id="messagelist">
                <c:forEach items="${messages }" var="message">
                    <tr id="${message.id}">
                        <td>
                            <input type="checkbox" class="checkboxitem">

                        </td>

                        <c:if test="${!controller.equals('draftBox')}">
                            <td class="mailbox-envelope"><a href="#">
                                <i
                                        class="fa fa-envelope<c:if test="${message.isread}">-o</c:if> text-yellow"></i></a>
                            </td>

                            <td class="mailbox-star"><a href="#"><i
                                class="fa fa-star<c:if test="${!message.mark}">-o</c:if> text-yellow"></i></a></td>

                        <td class="mailbox-name"><a
                                href="read-mail.html">${message.fromName }</a></td>
                            <td class="mailbox-subject"><a href="javascript:void(0);" style="color:black"
                                                           onclick="readMail(this)"><b>${message.subject }</b>
                            </a></td>
                            <td class="mailbox-attachment"></td>
                            <td class="mailbox-date" id="sendtime">${message.sendtime }</td>
                            <td class="addClassifyBtn"><a href="javascript:void(0)"><i class="fa fa-plus messageAddClassify" ></i></a> </td>

                        </c:if>

                        <c:if test="${controller.equals('draftBox')}">
                            <td class="mailbox-name"><a
                                    href="read-mail.html">
                                    <c:if test="${empty message.to}">(未填写接收方)</c:if>
                                    <c:if test="${not empty message.to}">${message.to}</c:if></a></td>
                            <td class="mailbox-subject"><a href="javascript:void(0)" class="draftSubject"><b>
                                <c:if test="${empty message.subject}">(未填写主题)</c:if>
                                <c:if test="${not empty message.subject}">${message.subject}</c:if>
                            </b></a></td>
                            <td class="mailbox-attachment"></td>
                            <td class="mailbox-date" id="sendtime">
                                <fmt:formatDate value='${message.saveTime }' pattern='yyyy-MM-dd HH:mm:ss'/>
                           </td>
                        </c:if>

                    </tr>
                </c:forEach>
                </tbody>
            </table>
            <!-- /.table -->
        </div>
        <!-- /.mail-box-messages -->
    </div>
    <!-- /.box-body -->
    <div class="box-footer no-padding">
        <div class="mailbox-controls">
            <!-- Check all button -->

            <div class="pull-right">
                ${currentPage.page}/${currentPage.totalPage}
                <div class="btn-group">
                    <button type="button" class="btn btn-default btn-sm" id="prevBtn">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <button type="button" class="btn btn-default btn-sm" id="nextBtn">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
                <!-- /.btn-group -->
            </div>
            <!-- /.pull-right -->
        </div>
    </div>
</div>
<script src="${pageContext.request.contextPath}/res/js/list.js"></script>
<script src="${pageContext.request.contextPath}/res/js/jquery-2.1.4.min.js"></script>
<script src="${pageContext.request.contextPath}/res/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/res/jstree/jstree.min.js"></script>
<script>


    $(function () {

        //邮件星标点击事件
        $(".mailbox-star").click(function (e) {
            e.preventDefault();
            //detect type
            var $this = $(this).find("a > i");
            var fa = $this.hasClass("fa-star");

            var id = $(this).parent().attr("id");

            if (fa) {
                $this.removeClass("fa-star").addClass("fa-star-o");
                $.post("${pageContext.request.contextPath}/manager/setStar.shtml", {"setStar": false, "id": id}, function () {
                    //星标邮件数-1
                    var starEle = $('#starBox > span');
                    var starNum = starEle.html();
                    starEle.html(parseInt(starNum)-1);
                    if((parseInt(starNum)-1) == 0){
                        starEle.hide();
                    }

                });
            } else {
                $this.removeClass("fa-star-o").addClass("fa-star");
                $.post("${pageContext.request.contextPath}/manager/setStar.shtml", {"setStar": true, "id": id},function(){
                    var starEle = $('#starBox > span');

                    var starNum = starEle.html();
                    starEle.html(parseInt(starNum)+1);
                    //星标邮件数+1
                    if(starEle.css("display") == "none"){
                        starEle.show();
                    }

                });
            }
        });

        //邮件全选
        $(".mailbox-envelope").click(function (e) {
            e.preventDefault();
            //detect type
            var $this = $(this).find("a > i");
            var fa = $this.hasClass("fa");
            var checked = $this.hasClass("fa-envelope-o");
            var isread = false;
            if (checked) {
                isread = true;
            }
            var id = $(this).parent().attr("id");

            setRead([id], isread);
            if (fa) {
                $this.toggleClass("fa-envelope");
                $this.toggleClass(" fa-envelope-o");
            }
        });

        //上一页按钮点击事件
        $("#prevBtn").click(function () {
            if (${currentPage.page} >
            1
            )
            {
                appendMailList({"page":${currentPage.prevPage}, "controller": "${controller}"})
            }

        })

//下一页按钮点击事件
        $("#nextBtn").click(function () {
            if (${currentPage.page} <
            ${currentPage.totalPage})
            {

                appendMailList({"page":${currentPage.nextPage}, "controller": "${controller}"})
            }
        })
        $("#checkall").click(function () {
            if ($(this).children().hasClass("fa-check-square-o")) {
                $(this).children().removeClass("fa-check-square-o");
                $(this).children().addClass("fa-square-o");
                $(".checkboxitem").prop("checked", false);

            } else {
                $(this).children().removeClass("fa-square-o");
                $(this).children().addClass("fa-check-square-o");
                $(".checkboxitem").prop("checked", true);
            }

        })

        //批量标记已读
        $("#markIsRead").click(function () {
            var checkItem = $(".checkboxitem:checked");
            var ids = new Array();
            checkItem.each(function () {
                var id = $(this).parent().parent().attr("id");
                var envelope = $(this).parent().next(".mailbox-envelope").find("a>i").removeClass('fa-envelope').addClass("fa-envelope-o");
                ids.push(id);
            })
            setRead(ids, false);
        })


        //批量删除
        $("#deleteMessage").click(function () {
            var checkItem = $(".checkboxitem:checked");
            var ids = new Array();
            checkItem.each(function () {
                var id = $(this).parent().parent().attr("id");
                $(this).parent().parent().remove();
                ids.push(id);
            });

            $.post('${pageContext.request.contextPath}/manager/deleteToTrash.shtml', {"ids": ids}, function () {
            });
        })

        //草稿箱条目点击事件
        $('.draftSubject').click(function (){
            var id =  $(this).parent().parent().attr("id");
            $("#variableContent").empty();
            $.get('${pageContext.request.contextPath}/mail/compose.shtml',{"id":id},function(data){

                $("#variableContent").append(data);
            })
        })



        $("#searchText").focus( function () {
            $(document).keypress(function (e) {
                // 回车键事件

                if (e.keyCode == 13) {
                    var searchStr = $('#searchText').val();
                    var map = {"searchText":searchStr,"page":1};
                    $.post('${pageContext.request.contextPath}/manager/searchMessage.shtml',map,function(data){
                        $('#variableContent').empty().html(data);
                    });
                }
            })
        });


        function addJSTreeEvent(){
            $('#jstree_div').on("changed.jstree", function (e, data) {
                var selectedItem = data.selected[0];
                var url = "${pageContext.request.contextPath}/classify/addMessage.shtml";
                $("#addClassifyBtn").show();
                $("#addClassifyBtn").click(function (){
                    $.post(url,{"name":selectedItem,"messageId":clickMessageId},function (data){
                        if(data){
                            alert("添加成功");
                        }else{
                            alert("分组已存在该邮件");
                        }
                    })
                    $("#addClassifyModal").hide();
                    $('#addClassifyModal').modal("hide");
                })
            });


        }

        var clickMessageId;
        $(".messageAddClassify").click(function (){
            $('#addClassifyModal').modal('show');
            clickMessageId = $(this).parent().parent().parent().attr("id");
            var url = "${pageContext.request.contextPath}/tree/listAllElement.shtml";
            if($("#jstree_div > ul").length){
                return ;
            }
            $("#jstree_div").empty().append("<ul></ul>");
            $.get(url,function (data){

                for(var i=0;i<data.length;i++){


                    $("#jstree_div>ul").append(' <li id="'+data[i].name+'"><a href="javascript:void(0)" class="treeItem">'+data[i].name+'</a></li>"');


                    if(data[i].child){
                        addJsTreeChild(data[i].child,data[i].name);
                    }
                }
                $('#jstree_div').jstree();
                addJSTreeEvent();
            })
        })

        function addJsTreeChild(child,parenntName){
            $("li[id='"+parenntName+"']").append("<ul></ul>");
            for(var i = 0;i<child.length;i++){
                $("li[id='"+parenntName+"'] > ul").append('<li id="'+child[i].name+'"><a href="javascript:void(0)" class="treeItem">'+child[i].name+'</a></li>');

                if(child[i].child){
                    addJsTreeChild(child[i].child,child[i].name);
                }
            }

        }





    })
</script>
